/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lct.eq2.backup;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 *
 * @author Me
 */
public class TestServer1 {

    public static void main(String args[]) throws ClassNotFoundException {
        // Create a non-blocking server socket and check for connections
        try {
            // Create a non-blocking server socket channel on port 80
            ServerSocketChannel ssChannel = ServerSocketChannel.open();
            ssChannel.configureBlocking(false);
            int port = 13267;
            ssChannel.socket().bind(new InetSocketAddress(port));
            // Accept the connection request.
            // If serverSocketChannel is blocking, this method blocks.
            // The returned channel is in blocking mode.
            while (true) {
                SocketChannel sChannel = ssChannel.accept();

                // If serverSocketChannel is non-blocking, sChannel may be null
                if (sChannel == null) {
                // There were no pending connection requests; try again later.
                // To be notified of connection requests,
                // see e179 Using a Selector to Manage Non-Blocking Server Sockets.
                } else {
                    ByteBuffer buf = ByteBuffer.allocateDirect(1024);

                    // Clear the buffer and read bytes from socket
                    buf.clear();
                    buf.flip();
                    int numBytesRead = sChannel.read(buf);
                    buf.compact();
                    if (numBytesRead == -1) {
                        // No more bytes can be read from the channel
                        sChannel.close();
                    } else {
                        // To read the bytes, flip the buffer

                        // Create an empty ByteBuffer with a 10 byte capacity
                        ByteBuffer bbuf = ByteBuffer.allocate(10);

                        // Get the ByteBuffer's capacity
                        int capacity = bbuf.capacity(); // 10

                        // Use the absolute get().
                        // This method does not affect the position.
                        byte[] b = new byte[5]; // position=0

                        // Use the relative get()
                        bbuf.get(b);
                        String tmp = new String(b);
                        System.out.println(tmp);

                    // Read the bytes from the buffer ...;
                    // see e159 Getting Bytes from a ByteBuffer
                    }

                }
            }
        // See e178 Accepting a Connection on a ServerSocketChannel
        // for an example of accepting a connection request
        } catch (IOException e) {
        }
    }
}
